package com.tianwen.management.filter;

import com.tianwen.management.config.JwtHelper;
import com.tianwen.management.entity.LoginUser;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: personnel-management
 * @description
 * @author: tianwen
 * @create: 2023-05-23 18:53
 **/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if(ObjectUtils.isEmpty(token)){
            filterChain.doFilter(request, response);
            return;
        }
        Long userId = null;

        try {
            userId = JwtHelper.getUserId(token);
        } catch (Exception e) {
            throw new RuntimeException("token");
        }


        LoginUser loginUser = (LoginUser)redisTemplate.opsForValue().get("user:"+userId.toString());
        if(loginUser==null){
            throw new RuntimeException("用户已过期");
        }
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(loginUser,null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
